package com.atguigu.mybatisplus.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

/**
 * 安全配置类
 * 该配置类用于配置Spring Security的相关参数，如密码编码器、安全过滤器链等。
 *
 * @author 86187
 * @date 2023/4/10 14:24
 */
@Configuration
public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf -> csrf.disable()) // 开发环境关闭CSRF
                .authorizeHttpRequests(auth -> auth
                        // 放行需要测试的接口（例如所有/api/**接口）
                        .requestMatchers("/api/**").permitAll()
                        .requestMatchers("/doc.html", "/swagger-ui/**", "/v3/api-docs/**").permitAll()
                        .requestMatchers("/webjars/**").permitAll()
                        // 其他接口仍需认证
                        .anyRequest().authenticated()
                );
        return http.build();
    }
}